<template>
    <div class="gold-shop-wrap">
        <van-nav-bar title="代理商查询" left-arrow fixed @click-left="onClickLeft" :class="{ scrolled: isScrolled }" />
        <!-- <div class="agent_box"> -->
        <!--  -->
        <div class="region_value">
            <div>
                <van-field style="width: 30%;" v-model="small_region_name" is-link readonly placeholder="请选择地区"
                    @click="smallShowPopup = true" />
                <van-field v-model="region_name" is-link readonly placeholder="请选择地区" @click="showPopup = true" />
            </div>
        </div>
        <!-- <div class="profit_core_title1">商家列表({{ total_count }})</div> -->
        <div style="margin-top: -.8rem;">
            <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
                <div class="order_all" v-for="item, index in shopList" :key="index" :title="item" @click="handleDeail(item)">
                    <div class="order_name_return">
                        <div
                            :class="item.status == 0 ? 'balance_amt info' : item.status == 1 ? 'balance_amt' : 'balance_amt success'">
                            {{ item.status == 0? '未签约' :item.status == 1?'已授权': "已签约" }}</div>
                        <div class="order_name_left">{{ item.region_full_name }}</div>
                    </div>
                </div>
            </van-list>
            <!-- </div> -->
        </div>

        <!-- 省市区 -->
        <van-popup v-model="bigShowPopup" position="bottom">
            <van-picker title="选择代理区域" value-key="name" show-toolbar :columns="bigAgentConfig" @confirm="onConfirmBig"
                @cancel="bigShowPopup = false" :value="cascaderValue" @change="bigChange" />
        </van-popup>
        <van-popup v-model="showPopup" position="bottom">
            <van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
                @change="onChange" @finish="onFinish" active-color="#1D69E4" />
        </van-popup>
        <van-popup v-model="smallShowPopup" position="bottom">
            <van-picker title="选择区域" value-key="name" show-toolbar :columns="smallAgentConfig" @change="onChangeSmall"
                @confirm="onConfirmSmall" @cancel="smallShowPopupCancel" :value="small_cascaderValue" />
        </van-popup>
    </div>
</template>
<script>
import { SHOP_DATA, AGENT_LIST, SHOP_RANGE, AGENT_REGION_LIST } from '@/api/mine'
export default {
    data() {
        return {
            finished: false,
            loading: false,
            amountList: {},
            page: 1,
            pageSize: 20,
            shopList: [],
            total_count: 0,
            level_name: this.$route.query.level_name,
            isScrolled: false,
            items: [],
            showPopup: false,
            rangeList: [],
            region_name: '',
            options: [],
            cascaderValue: '',
            tabIndex: 0,
            levels: 0,
            key: '',
            region_code: '',

            bigShowPopup: false,
            big_region_name: '',
            bigAgentConfig: [],
            big_cascaderValue: '',

            small_region_name: '',
            smallShowPopup: false,
            small_cascaderValue: 0,
            smallAgentConfig: [
                {
                    id: 0,
                    name: '省'
                }, {
                    id: 1,
                    name: '市'
                }
                // , {
                //     id: 2,
                //     name: '区'
                // }
            ],
        }
    },
    mounted() {
        window.scrollTo(0, 0)
        // this.fetchRegions(1, 0)
        localStorage.removeItem('amountList')
        window.addEventListener("scroll", this.handleScroll);
        // this.shopDataList()
        // this.$http.get(SHOP_RANGE).then(res => {
        //     this.bigAgentConfig = res.data
        // })
        //
    },
    beforeDestroy() {
        window.removeEventListener("scroll", this.handleScroll);

    },
    methods: {
        handleScroll() {
            // console.log(window.scrollY);

            this.isScrolled = window.scrollY > 26;
        },
        resetInit() { //重置
            this.page = 1;
            this.shopList = [];
            this.finished = false;
            this.loading = true;
            this.onLoad()
        },
        handleDeail(item){
            if(item.view_status!=0){
                this.$router.push({ name: 'agent_detail', query: {code:item.region_code} })

            }else{
                this.$toast('暂无权限查看')
            }
        },
        onClickLeft() {
            this.$router.back()
        },
        onConfirmBig(value) {
            this.big_cascaderValue = value.key
            this.levels = value.level
            this.big_region_name = value.name
            this.bigShowPopup = false
            // this.shopDataList()
            this.resetInit()
            // this.onLoad()
        },
        bigChange() {
            this.small_cascaderValue = ''
            this.small_region_name = ''
            this.cascaderValue = ''
            this.region_name = ''
            this.small_cascaderValue = ''
            this.key = ''
            this.region_code = ''
        },
        onConfirmSmall(value) {
            this.small_cascaderValue = value.id
            this.small_region_name = value.name
            this.smallShowPopup = false
            this.cascaderValue = ''
            this.region_name = ''
            this.fetchRegions(1, value.id)

        },
        smallShowPopupCancel() {
            this.smallShowPopup = false
            this.small_cascaderValue = ''
            this.small_region_name = ''
            this.cascaderValue = ''
            this.region_name = ''
            this.resetInit()
        },
        onChangeSmall() {

        },
        // 选择器变化时的回调
        onChange(res) {
            this.tabIndex = res.tabIndex
            if (this.tabIndex === this.small_cascaderValue) {
                return;
            }

            //点击加载下一级回调
            this.getSpaceListAgain(res.selectedOptions, res.value);
        },
        getSpaceListAgain(selectedOptions, value) {
            this.$http
                .get(AGENT_REGION_LIST, {
                    params: {
                        code: value,
                    },
                })
                .then((res) => {
                    const {
                        data
                    } = res;

                    if (this.tabIndex == 2 && !data.length) {
                        data = [{
                            code: 0,
                            name: '暂不选择',
                            parent_code: value
                        }]
                    }

                    if (data && data.length) {
                        this.setOptions(selectedOptions, data);
                    }
                });
        },
        setOptions(selectedOptions, data) {
            let _options = this.options;
            selectedOptions.forEach((item, index) => {
                if (index) {
                    //不是第一个则取下一级children
                    _options = _options.children;
                }
                _options =
                    _options[_options.findIndex((_item) => _item.value === item.value)];
            });
            console.log(selectedOptions);

            //找到最后一级
            let index = this.small_cascaderValue == 2 ? 1 : this.small_cascaderValue == 1 ? 0 : -1;
            console.log(this.tabIndex, index);

            _options.children = data.map((item) => {
                return {
                    text: item.name,
                    value: item.code,
                    children: (this.tabIndex === index || index === -1) ? null : [],
                };
            });
        },
        // 确定省市区
        onFinish({
            selectedOptions
        }) {
            this.showPopup = false;

            this.selectAreaList = selectedOptions;

            selectedOptions = selectedOptions.filter((item) => {
                return item.value !== 0;
            });

            this.region_name = selectedOptions.map((option) => option.text).join("/");
            // this.shopDataList()
            this.resetInit()
        },
        async fetchRegions(parentCode, level) {
            const res = await this.$http.get(AGENT_REGION_LIST, {
                params: {
                    code: parentCode,
                },
            });
            const { data } = res;
            // 确保 that 是正确的上下文（可以使用箭头函数）
            if (level == 0) {
                this.options = []
                data.forEach((item) => {
                    // console.log(item);
                    this.options.push({
                        text: item.name,
                        value: item.code,
                        children: null,
                    })
                });
            } else {
                this.options = []
                data.forEach((item) => {
                    this.options.push({
                        text: item.name,
                        value: item.code,
                        children: [],
                    })
                });
            }

            return
            if (level === 0) {
                data.forEach((item) => {
                    this.options.push({
                        text: item.name,
                        value: item.code,
                        children: [],
                    });
                });
            } else if (level === 1) {
                // 市级数据
                const province = this.options.find((item) => {
                    return item.value === parentCode; // 根据您的条件进行判断
                });
                if (province) {
                    province.children = data.map((item) => ({
                        text: item.name,
                        value: item.code,
                        children: [],
                    }));
                }
            } else if (level === 2) {
                // 区/县级数据
                this.options.forEach((province) => {
                    const city = province.children.find(
                        (item) => item.value === parentCode
                    );
                    if (city) {
                        city.children = data.map((item) => ({
                            text: item.name,
                            value: item.code,
                            children: [],
                        }));
                    }
                });
            }
            // }
        },
        // 查看更多
        getStatistics() {
            localStorage.setItem('amountList', JSON.stringify(this.items))
            let params = {
                key: this.big_cascaderValue,
                region_code: this.cascaderValue
            }
            localStorage.setItem('amountListPage', JSON.stringify(params))
            this.$router.push({ name: 'profitCoreStatistics' })
        },
        onLoad() {
            let params = {};
            params['page_num'] = this.page;
            params['page_size'] = this.pageSize;
            // params['key'] = this.big_cascaderValue;
            if (this.cascaderValue) {
                params['region_code'] = this.cascaderValue;
            }
            // this.shopList = [{ name: '555', status: 0 }, { name: '内蒙古自治区呼和浩特市托克托县服务中心服务中心', status: 1 }]
            // return
            // params['status'] = this.active;
            this.$http.get(AGENT_LIST, { params: params })
                .then(res => {
                    const {
                        list
                    } = res.data;
                    this.total_count = res.data.pages.total_count
                    if (list && list.length) {
                        this.page++;
                        this.shopList = this.shopList.concat(list);

                        // 加载状态结束
                        this.loading = false;
                        if (list.length < this.pageSize) {
                            this.finished = true;
                        }
                    } else {
                        this.finished = true;
                    }
                })
        },
    },
}
</script>
<style lang="scss" scoped>
.gold-shop-wrap {
    min-height: calc(100vh - 46px);
    padding-top: 46px;
    background: #F2F4F5;

    ::v-deep .van-hairline--bottom::after {
        border: none;
    }

    ::v-deep .van-icon {
        color: #fff;
    }

    ::v-deep .van-nav-bar__title {
        width: 150px;
        color: #fff;
    }

    ::v-deep .van-nav-bar__arrow {
        font-size: 20px;
    }

    ::v-deep .van-nav-bar__text {
        color: #fff;
    }

    ::v-deep .van-nav-bar {
        background: transparent;
        position: fixed; // 改为固定定位
        top: 0; // 添加这行
        left: 0; // 添加这行
        right: 0; // 添加这行
        z-index: 1000; // 添加这行，确保它在其他元素之上

        // position: fixed;
        &.scrolled {
            background-color: #ffffff; // 或者你想要的任何颜色

            .van-nav-bar__title,
            .van-icon,
            .van-nav-bar__text {
                color: #333; // 滚动后变为黑色
            }
        }
    }
}

.order_all {
    width: 95%;
    margin: 0 auto;
    margin-top: 0.24rem;
    // border: 0.01rem solid #999;
    border-radius: 0.16rem;
    background: #fff;

    .order_name_return {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 0.28rem;
        padding: 0.24rem .28rem;
        // padding-bottom: 0;
        // border-bottom: 0.01rem solid #999;
        box-sizing: border-box;

        .order_name_left {
            width: calc(100% - 1.5rem);
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: .28rem;
            color: #333333;
            line-height: 20px;
            text-align: left;
            font-style: normal;
        }

        .balance_amt {
            width: 1.32rem;
            box-sizing: border-box;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: .28rem;
            color: #1D69E4;
            // line-height: 20px;
            text-align: center;
            font-style: normal;
            background: #EBF1FC;
            border-radius: .12rem;
            border: 1px solid #5991EB;
            padding: .08rem 0;
        }

        .success {
            color: #52C41A;
            background: #F2FFE5;
            border-radius: .12rem;
            border: 1px solid #AAEC6E;
        }

        .info {
            color: #7E7E7E;
            border-radius: .12rem;
            background: #F0F0F0;
            border: 1px solid #999999;
        }

        // &_right {
        //     font-size: 0.25rem;
        // }
    }
}

.region_value {
    width: 100%;
    height: 2.2rem;
    background: url('../../images/icon_bg.png') no-repeat left;
    background-size: cover;
    position: relative;
    /* 相对定位 */
    top: -46px;

    /* 根据你的 NavBar 高度调整，Vant UI 默认 NavBar 高度为 46px */
    div {
        width: 95%;
        margin: 0 auto 0 auto;
        display: flex;
        justify-content: space-between;

        .van-cell {
            margin-top: 1.2rem;
            width: 65%;
            height: .72rem;
            border-radius: .15rem;
            padding: .12rem;
            box-sizing: border-box;

            ::v-deep .van-icon {
                color: #cdcbcb;
            }
        }
    }

}
</style>
